package com.example.draw;

import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

/**
 * <p>用于绘画长方形</p>
 *
 * @author dc
 * @date 2025-09-29
 **/
public class DrawRectangle extends Rectangle implements DrawShape {
    private static DrawShape drawShape;
    
    public DrawRectangle() {
        super();
        setFill(Color.TRANSPARENT);
        setStroke(Color.RED);
        setStrokeWidth(2);
        setMouseTransparent(true);
        setSmooth(false);  // 禁用平滑以获得更清晰的线条
    }
    public DrawRectangle(Color color, double thickness) {
        super();
        setFill(Color.TRANSPARENT);
        setStroke(color);
        setStrokeWidth(thickness);
        setMouseTransparent(true);
        setSmooth(false);  // 禁用平滑
    }

    @Override
    public double getDrawThickness() {
        return getStrokeWidth();
    }

    @Override
    public Color getDrawColor() {
        return (Color) getStroke();
    }

    @Override
    public void updateShape(Rectangle selectionArea, double startPointX, double startPointY, double x, double y) {
        // 计算绘图图形对于选中区域左上点的相对坐标
        double relativeStartX = startPointX - selectionArea.getX();
        double relativeStartY = startPointY - selectionArea.getY();
        double relativeX = x - selectionArea.getX();
        double relativeY = y - selectionArea.getY();
        if (relativeX > selectionArea.getWidth()) {
            relativeX = selectionArea.getWidth();
        }
        if (relativeY > selectionArea.getHeight()) {
            relativeY = selectionArea.getHeight();
        }
        if (relativeX < 0) {
            relativeX = 0;
        }
        if (relativeY < 0) {
            relativeY = 0;
        }
        
        // 计算绘图的基点坐标，开始点和当前点哪个的x选哪个，哪个的y小选那个
        double baseX = Math.min(relativeStartX, relativeX);
        double baseY = Math.min(relativeStartY, relativeY);
        double width = Math.abs(relativeStartX - relativeX);
        double height = Math.abs(relativeStartY - relativeY);
        
        setX(baseX);
        setY(baseY);
        setWidth(width);
        setHeight(height);
    }
    /**
     * 单线程下简单的单例获取实现
     * @return 单例
     */
    public static DrawShape getSingleInstance() {
        if (drawShape == null) {
            drawShape = new DrawRectangle();
        }
        return drawShape;
    }
    public static void clearSingleInstance() {
        drawShape = null;
    }
    
}
